<template>
  <view class="w-full">
    <!-- <view class="text-[24rpx] text-[#999] py-[32rpx] w-full flex-center">报名列表</view>
    <view class="flex flex-center">共{{ registrationList?.length || 0 }}人</view> -->

    <!-- 申请用户列表 -->
    <view class="pt-[20rpx] pb-[32rpx] mt-10rpx">
      <view v-if="!registrationList.length" class="flex flex-col items-center justify-center py-[100rpx] bg-white rounded-[28rpx]">
        <view class="w-[160rpx] h-[160rpx] bg-gradient-to-br from-[#e3f2fd] to-[#bbdefb] rounded-full flex items-center justify-center mb-[30rpx]">
          <IconFont font-class-name="iconfont" class-prefix="icon" name="dingdan" size="80" color="#2196F3" />
        </view>
        <view class="text-[30rpx] font-medium text-[#666]">暂无申请者</view>
      </view>

      <view class="flex flex-col gap-y-[20rpx]">
        <!-- 申请用户卡片 -->
        <view
          v-for="(applicant, index) in registrationList"
          :key="applicant.id"
          class="bg-white rounded-[24rpx] p-[24rpx] shadow-md relative"
          :class="isCurrentUserExecutor(applicant) ? 'border-2 border-red-500' : ''"
        >
          <!-- 状态标签 - 右上角 -->
          <view
            v-if="applicant.status == 10"
            class="absolute top-[16rpx] right-[16rpx] px-[16rpx] py-[8rpx] rounded-[12rpx] text-[20rpx] font-medium bg-[#ffebee] text-[#f44336] border border-[#ffcdd2]"
          >
            ❌ 已拒绝
          </view>
          <view
            v-else-if="applicant.status == 11 || applicant.status > 20"
            class="absolute top-[16rpx] right-[16rpx] px-[16rpx] py-[8rpx] rounded-[12rpx] text-[20rpx] font-medium bg-[#e8f5e9] text-[#4caf50] border border-[#c8e6c9]"
          >
            ✅ 已通过
          </view>
          <view v-else class="absolute top-[16rpx] right-[16rpx] px-[16rpx] py-[8rpx] rounded-[12rpx] text-[20rpx] font-medium bg-[#fff3e0] text-[#ff9800] border border-[#ffe0b2]"> ⏳ 待审核 </view>
          <!-- 用户基本信息 -->
          <view class="flex items-start justify-between mb-[20rpx]">
            <view class="flex items-center flex-1" @click="goToUserDetail(applicant)">
              <!-- 用户头像 -->
              <image :src="applicant.avatar_url || defaultAvatar" class="w-[80rpx] h-[80rpx] rounded-full mr-[16rpx] flex-shrink-0 user-avatar" mode="aspectFill" @error="handleAvatarError" />

              <view class="flex-1">
                <view class="flex items-center mb-[8rpx]">
                  <text class="text-[28rpx] font-bold text-[#333] mr-[12rpx]"> {{ applicant.name }} </text>
                </view>

                <!-- 用户标签 -->
                <view class="flex items-center gap-x-[8rpx] mb-[8rpx]">
                  <view v-for="tag in applicant.tags" :key="tag" class="px-[8rpx] py-[2rpx] bg-[#f5f5f5] text-[#666] text-[20rpx] rounded-[6rpx]">
                    {{ tag }}
                  </view>
                </view>

                <!-- 申请时间 -->
                <text class="text-[22rpx] text-[#999]"> 申请时间：{{ applicant.create_time }} </text>
              </view>
            </view>
          </view>

          <!-- 任务状态显示 -->
          <view class="stage-status flex items-center gap-[10rpx] mb-[16rpx]">
            <view class="text-[20rpx] text-[#999]">任务状态:</view>
            <text class="text-[20rpx]" :class="getStatusTextColor(applicant.status)">
              {{ getStatusLabel(applicant.status) }}
            </text>
            <template v-if="applicant.amount">
              <text class="text-[20rpx]" v-if="applicant.new_price && applicant.new_price != applicant.amount">
                <text class="text-[20rpx] text-[#999] line-through">¥{{ applicant.amount }}</text>
                <text class="text-[20rpx] text-[#ff0000]">￥{{ applicant.new_price }}</text>
              </text>
              <text class="text-[20rpx] text-[#ff0000]" v-else>￥{{ applicant.amount }}</text>
            </template>
          </view>

          <!-- 操作按钮 -->
          <view class="flex items-center gap-x-[12rpx]" v-if="!applicant.status && props.isPublisher">
            <nut-button size="small" type="default" class="flex-1" @click="handleContact(applicant)"> 立即联系 </nut-button>
            <nut-button v-if="!applicant.status" size="small" type="default" class="flex-1" @click="checkContact(applicant)"> 审核 </nut-button>
          </view>

          <!-- 功能按钮 - 根据状态和角色显示 -->
          <view class="flex flex-wrap items-center gap-2 mt-[16rpx]" v-if="applicant.status == 11 || applicant.status > 20">
            <!-- 发布者操作按钮 -->
            <template v-if="props.isPublisher">
              <nut-button
                v-for="(action, i) in getPublisherActions(applicant.status)"
                :key="i"
                size="small"
                type="primary"
                class="flex-1"
                @click="handlePublisherAction(applicant.id, index, action, applicant.status)"
              >
                {{ action }}
              </nut-button>
              <nut-button size="small" type="default" class="flex-1" @click="showCheckinDetail(applicant)" v-if="ttype == 3">
                签到详情
              </nut-button>
            </template>

            <!-- 执行者操作按钮 -->
            <template v-for="(action, i) in getExecutorActions(applicant.status)" :key="i">
              <nut-button size="small" type="default" class="flex-1" @click="handleExecutorAction(applicant.id, index, action, applicant.status)" v-if="isCurrentUserExecutor(applicant)">
                {{ action }}
              </nut-button>
            </template>
            <nut-button size="small" type="default" class="flex-1" @click="showCheckinDetail(applicant)" v-if="isCurrentUserExecutor(applicant) && ttype == 3">
              签到详情
            </nut-button>

          </view>

          <!-- 评价按钮 - 仅对已完成的用户显示 -->
          <view v-if="applicant.status === 'accepted'" class="mt-[12rpx]">
            <nut-button
              size="small"
              type="default"
              class="w-full border-yellow-500 text-yellow-500 bg-transparent rounded-[20rpx] py-[12rpx] text-[24rpx] font-medium hover:bg-yellow-50 transition-all duration-200"
              @click="navigateToEvaluate(applicant)"
            >
              评价用户
            </nut-button>
          </view>
        </view>
      </view>

      <!-- 空状态 -->
      <!-- <view v-if="applicants.length === 0" class="flex flex-col items-center justify-center py-[120rpx]">
        <text class="text-[28rpx] text-[#999] mb-[16rpx]">暂无申请用户</text>
        <text class="text-[24rpx] text-[#ccc]">等待用户申请中...</text>
      </view> -->
      <view class="h-[120rpx]"></view>
    </view>



    <!-- VIP 次卡确认弹窗 -->
    <VipCardConfirmModal v-model:visible="showVipConfirm" :card-balance="userInfo.card_balance || 0" @confirm="onVipConfirm" @cancel="onVipCancel" />

    <!-- 修改金额弹窗 -->
    <nut-popup v-model:visible="showAmountDialog" position="center">
      <view class="amount-dialog bg-white rounded-xl p-[40rpx] w-[540rpx]">
        <view class="dialog-header text-center mb-[40rpx]">
          <text class="text-[36rpx] font-bold text-[#212529]">修改金额</text>
        </view>

        <view class="dialog-content">
          <view class="amount-info mb-[30rpx]">
            <text class="text-[28rpx] text-[#666666]">原金额：</text>
            <text class="text-[32rpx] font-bold text-[#f72585]">¥{{ currentAmount }}</text>
          </view>

          <view class="input-group mb-[30rpx]">
            <text class="text-[28rpx] text-[#666666] mb-[16rpx] block">新金额：</text>
            <nut-input v-model="newAmount" type="digit" placeholder="请输入新金额" class="amount-input" :style="{ border: '2rpx solid #e9ecef', borderRadius: '12rpx', padding: '20rpx' }" />
            <text v-if="amountError" class="text-[24rpx] text-[#FF4D4F] mt-[8rpx] block">{{ amountError }}</text>
          </view>

          <view class="password-group mb-[40rpx]">
            <text class="text-[28rpx] text-[#666666] mb-[16rpx] block">交易密码：</text>
            <nut-input
              v-model="amountPassword"
              type="password"
              placeholder="请输入6位交易密码"
              maxlength="6"
              class="password-input"
              :style="{ border: '2rpx solid #e9ecef', borderRadius: '12rpx', padding: '20rpx' }"
            />
            <text v-if="passwordError" class="text-[24rpx] text-[#FF4D4F] mt-[8rpx] block">{{ passwordError }}</text>
          </view>
        </view>

        <view class="dialog-actions flex gap-[20rpx]">
          <nut-button type="default" class="flex-1" @click="cancelAmountChange"> 取消 </nut-button>
          <nut-button type="primary" class="flex-1" @click="confirmAmountChange" :loading="isUpdatingAmount"> 确定 </nut-button>
        </view>
      </view>
    </nut-popup>

    <!-- 确认完成弹窗 -->
    <nut-popup v-model:visible="showConfirmCompleteDialog" position="center">
      <view class="amount-dialog bg-white rounded-xl p-[40rpx] w-[540rpx]">
        <view class="dialog-header text-center mb-[40rpx]">
          <text class="text-[36rpx] font-bold text-[#212529]">确认完成</text>
        </view>

        <view class="dialog-content">
          <view class="amount-info mb-[30rpx]">
            <text class="text-[28rpx] text-[#666666]">任务金额：</text>
            <text class="text-[32rpx] font-bold text-[#f72585]">¥{{ currentTaskAmount }}</text>
          </view>

          <view class="password-group mb-[40rpx]">
            <text class="text-[28rpx] text-[#666666] mb-[16rpx] block">支付密码：</text>
            <nut-input
              v-model="confirmCompletePassword"
              type="password"
              placeholder="请输入6位支付密码"
              maxlength="6"
              class="password-input"
              :style="{ border: '2rpx solid #e9ecef', borderRadius: '12rpx', padding: '20rpx' }"
            />
            <text v-if="confirmCompletePasswordError" class="text-[24rpx] text-[#FF4D4F] mt-[8rpx] block">{{ confirmCompletePasswordError }}</text>
          </view>
        </view>

        <view class="dialog-actions flex gap-[20rpx]">
          <nut-button type="default" class="flex-1" @click="cancelConfirmComplete"> 取消 </nut-button>
          <nut-button type="primary" class="flex-1" @click="confirmComplete" :loading="isConfirmingComplete"> 确定 </nut-button>
        </view>
      </view>
    </nut-popup>

    <!-- 审核弹窗 -->
    <nut-overlay v-model:visible="auditModalVisible" z-index="3000">
      <view class="audit-modal flex items-center justify-center h-full">
        <view class="audit-content bg-white rounded-[24rpx] w-[600rpx] mx-[32rpx] p-[40rpx]">
          <!-- 弹窗头部 -->
          <view class="audit-header text-center mb-[32rpx]">
            <text class="text-[36rpx] font-bold text-[#333]">申请审核</text>
          </view>

          <!-- 用户信息 -->
          <view class="user-info flex items-center mb-[32rpx] p-[24rpx] bg-[#f8f9fa] rounded-[16rpx]">
            <image :src="currentAuditUser.avatar_url || defaultAvatar" class="w-[80rpx] h-[80rpx] rounded-full mr-[16rpx] flex-shrink-0 user-avatar" mode="aspectFill" @error="handleAvatarError" />
            <view class="user-details flex-1">
              <text class="block text-[28rpx] font-medium text-[#333] mb-[8rpx]">申请人：{{ currentAuditUser.name }}</text>
              <text class="text-[24rpx] text-[#666]">申请时间：{{ currentAuditUser.create_time }}</text>
            </view>
          </view>

          <!-- 申请理由 -->
          <!-- <view v-if="currentAuditUser.reason" class="apply-reason mb-[32rpx]">
              <text class="block text-[26rpx] font-medium text-[#333] mb-[12rpx]">📝 申请理由：</text>
              <text class="text-[24rpx] text-[#666] leading-[1.6] block p-[16rpx] bg-[#f8f9fa] rounded-[12rpx]">{{
                currentAuditUser.reason }}</text>
            </view> -->

          <!-- 操作按钮 -->
          <view class="audit-actions flex gap-[16rpx]">
            <nut-button size="large" type="default" class="flex-1" @click="handleAuditCancel"> 取消 </nut-button>
            <nut-button size="large" type="danger" class="flex-1" :loading="auditLoading" @click="handleAuditApprove(0)"> 不通过 </nut-button>
            <nut-button size="large" type="success" class="flex-1" :loading="auditLoading" @click="handleAuditApprove(1)"> 通过 </nut-button>
          </view>
        </view>
      </view>
    </nut-overlay>
  </view>
</template>

<script setup>
import { ref, onMounted } from "vue";
import Taro from "@tarojs/taro";
import { IconFont } from "@nutui/icons-vue-taro";
// import { Overlay as nutOverlay } from "@nutui/nutui-taro";
import { post } from "@/utils/request";
// import EmptyState from "./components/EmptyState.vue";

import { getCurrentInstance } from "@tarojs/runtime";
import defaultAvatar from "@/assets/pic/ren.png";
import { StatusActions } from "@/constants/StatusActions";
import { useUserStore } from "@/store/user";
import { storeToRefs } from "pinia";
import VipCardConfirmModal from "@/components/VipCardConfirmModal.vue";

const props = defineProps({
  tid: { type: String, default: "" },
  type: { type: String, default: "0" },
  isPublisher: { type: Boolean, default: false },
  publisherId: { type: String, default: "" },
});
const totalAmount = ref(0);

const emit = defineEmits(["list", "refresh"]);
/**
 * 申请用户管理列表页面
 * 显示申请用户信息，提供联系和接受申请功能
 */
// 使用 props 中的 type，如果没有传递则默认为 0（日结）
const type = parseInt(props.type) || 0;
console.log("type 哈哈", type);
const ttype = ref(type);

const showCheckinDetail = (item) => {
  console.log("item==>", item);
  Taro.navigateTo({
    // url: `/pages-detail/post/reward/checkin-task-detail?id=${props.tid}&type=3`,
    url: `/pages/post/sign-list?memberId=${item.member_id}&id=${item.task_id}`,
  });
};

// 用户信息相关
const userStore = useUserStore();
const { userInfo } = storeToRefs(userStore);

const statusMap = {
  1: "发布中",
  2: "进行中",
  3: "待确认完成",
  4: "确认没完成",
  5: "确认已完成",
  6: "已评价",
};

const buttonMap = {
  1: [],
  2: ["聊天", "接受", "拒绝"],
  3: ["聊天", "验证完成", "有纠纷"],
  4: [],
  5: ["去评价"],
  6: [],
};

// 任务信息
const taskInfo = ref({
  title: "超市临时导购员（周末2天）",
  status: "执行中",
  statusClass: "bg-[#f6ffed] text-[#52c41a]",
  amount: "￥180/天",
  deadline: "本周日 22:00",
});

// 申请用户列表
const applicants = ref([]);

// VIP 次卡确认弹窗
const showVipConfirm = ref(false);
const pendingAction = ref(null);

// 修改金额相关状态
const showAmountDialog = ref(false);
const newAmount = ref("");
const currentAmount = ref(0);
const currentApplicantId = ref(0);
const currentApplicantIndex = ref(0);
const amountError = ref("");
const isUpdatingAmount = ref(false);
const amountPassword = ref("");
const passwordError = ref("");

// 确认完成弹窗相关状态
const showConfirmCompleteDialog = ref(false);
const confirmCompletePassword = ref("");
const confirmCompletePasswordError = ref("");
const isConfirmingComplete = ref(false);
const currentTaskAmount = ref(0);

/**
 * 计算两个日期之间的天数差
 * @param startDate 开始日期字符串 (格式: "2025-09-02")
 * @param endDate 结束日期字符串 (格式: "2025-09-02")
 * @returns 天数差
 */
const calculateDays = (startDate, endDate) => {
  if (!startDate || !endDate) return 0;

  try {
    const start = new Date(startDate);
    const end = new Date(endDate);

    // 计算时间差（毫秒）
    const timeDiff = end.getTime() - start.getTime();

    // 转换为天数（向上取整，包含开始和结束日期）
    const daysDiff = Math.ceil(timeDiff / (1000 * 3600 * 24)) + 1;

    return daysDiff > 0 ? daysDiff : 0;
  } catch (error) {
    console.error("日期计算错误:", error);
    return 0;
  }
};

/**
 * 获取发布者操作按钮列表
 * @param status 任务状态码
 * @returns 操作按钮数组
 */
const getPublisherActions = (status) => {
  // 申请状态映射到任务状态
  const statusMapping = {
    11: "3", // 已通过 -> 待完成（发布者等待执行者提交）
  };

  // 如果状态在映射中，使用映射后的状态
  const mappedStatus = statusMapping[status] || status;
  console.log("mappedStatus=======", mappedStatus, status, StatusActions);
  return StatusActions[mappedStatus]?.publisherActions || [];
};

/**
 * 获取执行者操作按钮列表
 * @param status 任务状态码
 * @returns 操作按钮数组
 */
const getExecutorActions = (status) => {
  // 申请状态映射到任务状态
  const statusMapping = {
    11: "0", // 已通过 -> 待完成（执行者可以提交"我已完成"）
  };

  // 如果状态在映射中，使用映射后的状态
  const mappedStatus = statusMapping[status] || status;
  console.log("mappedStatus=======", mappedStatus, status, StatusActions);
  return StatusActions[mappedStatus]?.executorActions || [];
};

/**
 * 判断当前用户是否为执行者
 * @param applicant 申请者信息
 * @returns 是否为执行者
 */
const isCurrentUserExecutor = (applicant) => {
  if (!userInfo.value || !applicant) return false;

  const currentUserId = userInfo.value.id;
  const applicantMemberId = applicant.member_id;

  console.log("当前用户ID:", currentUserId, "类型:", typeof currentUserId);
  console.log("申请者member_id:", applicantMemberId, "类型:", typeof applicantMemberId);

  // 转换为字符串进行比较
  const isExecutor = String(currentUserId) === String(applicantMemberId);
  console.log("是否为执行者:", isExecutor);

  return isExecutor;
};

/**
 * 获取状态标签文字
 * @param status 任务状态码
 * @returns 状态标签文字
 */
const getStatusLabel = (status) => {
  // 申请状态映射
  const applicationStatusMap = {
    10: "已拒绝",
    11: "待完成",
  };

  // 优先使用申请状态映射，然后使用 StatusActions
  return applicationStatusMap[status] || StatusActions[status]?.label || "未知状态";
};

/**
 * 获取状态文字颜色
 * @param status 任务状态码
 * @returns CSS类名
 */
const getStatusTextColor = (status) => {
  switch (status) {
    case 0:
      return "text-[#FF4D4F]"; // 待完成 - 红色
    case 3:
      return "text-[#52C41A]"; // 已完成 - 绿色
    case 21:
      return "text-[#FAAD14]"; // 待审核 - 橙色
    case 22:
      return "text-[#52C41A]"; // 确认完成 - 绿色
    case 23:
    case 24:
      return "text-[#FF4D4F]"; // 有纠纷/纠纷协商 - 红色
    case 10:
      return "text-[#FF4D4F]"; // 已拒绝 - 红色
    case 11:
      return "text-[#52C41A]"; // 已通过 - 绿色
    default:
      return "text-[#666666]"; // 默认灰色
  }
};

/**
 * 处理发布者操作
 * @param applicantId 申请者ID
 * @param index 索引
 * @param action 操作名称
 * @param currentStatus 当前状态
 */
const handlePublisherAction = async (applicantId, index, action, currentStatus) => {
  console.log("action==>", action);
  try {
    let newStatus = currentStatus;

    // 根据操作名称确定新状态
    switch (action) {
      case "评价":
        // 跳转到评价页面
        const applicant = registrationList.value[index];
        console.log("applicant==> 555", applicant, taskInfo);
        if (applicant) {
          // 跳转到评价页面，传递必要参数
          Taro.navigateTo({
            url: `/pages-detail/post/recruit/evaluate?taskId=${applicant.id}&userName=${encodeURIComponent(applicant.name)}&userAvatar=${encodeURIComponent(applicant.avatar_url || '')}&taskName=${encodeURIComponent(taskInfo.value.title || '')}&userId=${applicant.member_id}&day=1&type=${type}`
          });
        } else {
          Taro.showToast({
            title: "获取申请者信息失败",
            icon: "error",
            duration: 2000,
          });
        }
        return;
      case "联系执行者":
        // 跳到聊天页面
        const currentApplicant = registrationList.value[index];
        if (currentApplicant && currentApplicant.member_id) {
          Taro.navigateTo({
            url: `/pages/message/chat?userId=${currentApplicant.member_id}`,
          });
        } else {
          Taro.showToast({
            title: "获取执行者信息失败",
            icon: "error",
            duration: 2000,
          });
        }
        return;
      case "确认完成":
        // 打开确认完成弹窗
        openConfirmCompleteDialog(applicantId, index);
        return;
      case "有纠纷":
        // 显示纠纷弹窗
        const disputeRes = await Taro.showModal({
          title: "有纠纷",
          content: "确定要标记为有纠纷吗？",
          confirmText: "确定",
          cancelText: "取消",
        });
        if (!disputeRes.confirm) return;
        newStatus = 23; // 有纠纷
        break;
      case "联系平台":
        // 显示客服联系弹窗
        Taro.navigateTo({
          url: `/pages/webs/contact-us`,
        });
        return;
      case "修改金额":
        // 打开修改金额弹窗
        console.log("修改金额");
        openAmountDialog(applicantId, index, totalAmount.value); // 这里使用默认金额，实际应该从数据中获取
        return;
      default:
        Taro.showToast({
          title: "未知操作",
          icon: "error",
          duration: 2000,
        });
        return;
    }

    // 调用接口更新状态
    const res = await post(getUpdateUrl(), {
      id: applicantId,
      status: newStatus,
    });

    if (res.code === 0) {
      // 更新本地状态
      registrationList.value[index].status = newStatus;

      Taro.showToast({
        title: "操作成功",
        icon: "success",
        duration: 2000,
      });
      emit("refresh");
    } else {
      Taro.showToast({
        title: res.data || "操作失败",
        icon: "error",
        duration: 2000,
      });
    }
  } catch (error) {
    console.error("发布者操作失败:", error);
    Taro.showToast({
      title: "网络错误，请重试",
      icon: "error",
      duration: 2000,
    });
  }
};

function getUpdateUrl(){
  const urlMaps = {
    0: "/recruitmentDaily/updateSignUp",
    1: "/task/updateSignUp",
    2: "/recruitment/updateSignUp",
    3: "/check/updateSignUp",
  };
  return urlMaps[type];
}

/**
 * 处理执行者操作
 * @param applicantId 申请者ID
 * @param index 索引
 * @param action 操作名称
 * @param currentStatus 当前状态
 */
const handleExecutorAction = async (applicantId, index, action, currentStatus) => {
  try {
    let newStatus = currentStatus;

    // 根据操作名称确定新状态
    switch (action) {
      case "我已完成":
        // 设置待处理的操作信息
        pendingAction.value = { applicantId, index };
        // 显示 VIP 次卡确认弹窗
        showVipConfirm.value = true;
        return;
      case "联系平台":
        // 显示客服联系弹窗
        Taro.navigateTo({
          url: `/pages/webs/contact-us`,
        });
        return;
      case "联系发布者":
        // 跳到聊天页面
        Taro.navigateTo({
            url: `/pages/message/chat?userId=${ props.publisherId }`,
          });
        return;
      case "接受方案":
        const acceptRes = await Taro.showModal({
          title: "接受方案",
          content: "确定要接受方案吗？",
          confirmText: "接受",
          cancelText: "取消",
        });
        if (!acceptRes.confirm) return;
        newStatus = 26; // 接受方案
        break;
      case "拒绝方案":
        const rejectRes = await Taro.showModal({
          title: "拒绝方案",
          content: "确定要拒绝方案吗？",
          confirmText: "拒绝",
          cancelText: "取消",
        });
        if (!rejectRes.confirm) return;
        newStatus = 25; // 拒绝方案
        break;
      default:
        Taro.showToast({
          title: "未知操作",
          icon: "error",
          duration: 2000,
        });
        return;
    }

    // 调用接口更新状态
    const res = await post(getUpdateUrl(), {
      id: applicantId,
      status: newStatus,
    });

    if (res.code === 0) {
      // 更新本地状态
      registrationList.value[index].status = newStatus;

      Taro.showToast({
        title: "操作成功",
        icon: "success",
        duration: 2000,
      });

      // 刷新列表
      emit("refresh");
    } else {
      Taro.showToast({
        title: res.data || "操作失败",
        icon: "error",
        duration: 2000,
      });
    }
  } catch (error) {
    console.error("执行者操作失败:", error);
    Taro.showToast({
      title: "网络错误，请重试",
      icon: "error",
      duration: 2000,
    });
  }
};

/**
 * VIP 次卡确认回调
 */
const onVipConfirm = async (payload) => {
  if (!pendingAction.value) {
    showVipConfirm.value = false;
    return;
  }

  const { applicantId, index } = pendingAction.value;
  pendingAction.value = null;

  try {
    // 更新状态为待审核
    const newStatus = 21;

    // 调用接口更新状态
    const res = await post(getUpdateUrl(), {
      id: applicantId,
      status: newStatus,
      countCard: 0,
      // countCard: payload.useVip ? 1 : 0, // 如果选择使用 VIP 次卡，传递额外参数
    });

    if (res.code === 0) {
      // 更新本地状态
      registrationList.value[index].status = newStatus;

      Taro.showToast({
        title: "提交成功，待审核",
        icon: "success",
        duration: 2000,
      });
      emit("refresh");
    } else {
      Taro.showToast({
        title: res.data || "操作失败",
        icon: "error",
        duration: 2000,
      });
    }
  } catch (error) {
    console.error("VIP 次卡确认操作失败:", error);
    Taro.showToast({
      title: "网络错误，请重试",
      icon: "error",
      duration: 2000,
    });
  }
};

/**
 * VIP 次卡确认取消回调
 */
const onVipCancel = () => {
  pendingAction.value = null;
  showVipConfirm.value = false;
};

/**
 * 打开修改金额弹窗
 * @param applicantId 申请者ID
 * @param index 索引
 * @param currentAmount 当前金额
 */
const openAmountDialog = (applicantId, index, num) => {
  currentApplicantId.value = applicantId;
  currentApplicantIndex.value = index;
  currentAmount.value = num;
  newAmount.value = num;
  amountError.value = "";
  amountPassword.value = "";
  passwordError.value = "";
  showAmountDialog.value = true;
};

/**
 * 打开确认完成弹窗
 * @param applicantId 申请者ID
 * @param index 索引
 */
const openConfirmCompleteDialog = (applicantId, index) => {
  currentApplicantId.value = applicantId;
  currentApplicantIndex.value = index;
  // 获取任务金额，这里需要根据实际情况获取
  currentTaskAmount.value = totalAmount.value || 0;
  confirmCompletePassword.value = "";
  confirmCompletePasswordError.value = "";
  showConfirmCompleteDialog.value = true;
};

/**
 * 取消修改金额
 */
const cancelAmountChange = () => {
  showAmountDialog.value = false;
  newAmount.value = "";
  amountError.value = "";
  amountPassword.value = "";
  passwordError.value = "";
};

/**
 * 取消确认完成
 */
const cancelConfirmComplete = () => {
  showConfirmCompleteDialog.value = false;
  confirmCompletePassword.value = "";
  confirmCompletePasswordError.value = "";
  currentTaskAmount.value = 0;
  currentApplicantId.value = 0;
  currentApplicantIndex.value = 0;
};

/**
 * 确认修改金额
 */
const confirmAmountChange = async () => {
  // 验证金额输入
  const amount = parseFloat(newAmount.value);

  if (isNaN(amount) || amount <= 0) {
    amountError.value = "请输入有效的金额";
    return;
  }

  if (amount > currentAmount.value) {
    amountError.value = "新金额不能超过原金额";
    return;
  }

  // 验证密码输入
  if (!amountPassword.value || amountPassword.value.length !== 6) {
    passwordError.value = "请输入6位交易密码";
    return;
  }

  // 清除错误提示
  amountError.value = "";
  passwordError.value = "";

  try {
    isUpdatingAmount.value = true;

    // 根据类型调用不同的接口修改金额
    const urlMaps = {
      0: "/recruitmentDaily/confirmPay",
      1: "/task/confirmPay", 
      2: "/recruitment/confirmPay",
      3: "/check/confirmPay",
    };
    
    const res = await post(urlMaps[type], {
      amount: amount,
      id: currentApplicantId.value,
      payPassword: amountPassword.value,
      // stage: 0
    });

    if (res.code === 0) {
      Taro.showToast({
        title: "金额修改成功",
        icon: "success",
        duration: 2000,
      });

      // 关闭弹窗并清空数据
      showAmountDialog.value = false;
      newAmount.value = "";
      amountPassword.value = "";
    } else {
      Taro.showToast({
        title: res.data || "金额修改失败",
        icon: "error",
        duration: 2000,
      });
    }
  } catch (error) {
    console.error("修改金额失败:", error);
    Taro.showToast({
      title: "网络错误，请重试",
      icon: "error",
      duration: 2000,
    });
  } finally {
    isUpdatingAmount.value = false;
  }
};

/**
 * 确认完成
 */
const confirmComplete = async () => {
  // 验证密码输入
  if (!confirmCompletePassword.value || confirmCompletePassword.value.length !== 6) {
    confirmCompletePasswordError.value = "请输入6位交易密码";
    return;
  }

  // 清除错误提示
  confirmCompletePasswordError.value = "";

  try {
    isConfirmingComplete.value = true;

    // 根据类型调用不同的确认完成接口
    const urlMaps = {
      0: "/recruitmentDaily/confirmPay",
      1: "/task/confirmPay", 
      2: "/recruitment/confirmPay",
      3: "/check/confirmPay",
    };
    
    const res = await post(urlMaps[type], {
      amount: currentTaskAmount.value,
      id: currentApplicantId.value,
      payPassword: confirmCompletePassword.value,
    });

    if (res.code === 0) {
      Taro.showToast({
        title: "确认完成成功",
        icon: "success",
        duration: 2000,
      });

      // 更新本地状态
      registrationList.value[currentApplicantIndex.value].status = 21; // 待审核

      // 关闭弹窗并清空数据
      showConfirmCompleteDialog.value = false;
      confirmCompletePassword.value = "";
    } else {
      Taro.showToast({
        title: res.data || "确认完成失败",
        icon: "error",
        duration: 2000,
      });
    }
  } catch (error) {
    console.error("确认完成失败:", error);
    Taro.showToast({
      title: "网络错误，请重试",
      icon: "error",
      duration: 2000,
    });
  } finally {
    isConfirmingComplete.value = false;
  }
};

const handleContact = (item) => {
  // 跳转到聊天页面
  console.log("===>", item);
  Taro.navigateTo({
    url: `/pages/message/chat?userId=${item.member_id}&userName=${item.name}`,
  });
};

/**
 * 处理头像加载错误
 * @param {Event} event - 图片加载错误事件
 */
const handleAvatarError = (event) => {
  // 设置默认头像
  event.target.src = defaultAvatar;
};

/**
 * 返回上一页
 */
const handleBack = () => {
  Taro.navigateBack();
};

/**
 * 审核申请用户
 * @param {Object} applicant - 申请用户信息
 */
const checkContact = (applicant) => {
  currentAuditUser.value = applicant;
  console.log("审核用户：", applicant);
  auditModalVisible.value = true;
};



// 审核弹窗相关
const auditModalVisible = ref(false);
const currentAuditUser = ref({});
const auditLoading = ref(false);

//获取数据
const receiveData = ref();
const registrationList = ref([]);

/**
 * 审核
 */
const handleAuditApprove = async (n) => {
  if (auditLoading.value) return;

  auditLoading.value = true;
  // const type = Taro.getCurrentInstance().router.params.type;
  const urlMaps = {
    0: "/recruitmentDaily/updateSignUp",
    1: "/task/updateSignUp",
    2: "/pages/post/my-publish",
  };

  try {
    let res = await post(urlMaps[type], {
      id: currentAuditUser.value.id,
      status: n == 0 ? 10 : 11,
    });
    if (res.code === 0) {
      // 关闭弹窗并刷新列表
      auditModalVisible.value = false;

      // 刷新申请列表
      const courseId = getCurrentInstance();
      const taskId = courseId.router?.params.taskId || "";
      if (taskId) {
        getSignUpList(taskId);
      }
    } else {
      Taro.showToast({
        title: res.data || "审核失败",
        icon: "none",
        duration: 2000,
      });
    }
  } catch (error) {
    console.error("审核不通过失败：", error);
    Taro.showToast({
      title: "网络异常，请重试",
      icon: "none",
      duration: 2000,
    });
  } finally {
    auditLoading.value = false;
  }
};

/**
 * 取消审核
 */
const handleAuditCancel = () => {
  auditModalVisible.value = false;
  currentAuditUser.value = {};
};

/**
 * 跳转到评价页面
 * @param {Object} applicant - 申请用户信息
 */
const navigateToEvaluate = (applicant) => {
  // 跳转到评价页面，传递必要参数
  Taro.navigateTo({
    url: `/pages-detail/post/recruit/evaluate?taskId=${props.tid}&userName=${encodeURIComponent(applicant.name)}&userAvatar=${encodeURIComponent(applicant.avatar || '')}&taskName=${encodeURIComponent(taskInfo.value.title || '')}&userId=${applicant.id || applicant.member_id}`
  });
};



/**
 * 接受申请
 * @param {Object} applicant - 申请用户信息
 */
const handleAccept = (applicant) => {
  // if (applicant.status === 'accepted' || applicant.status === 'rejected') {
  //   return;
  // }

  Taro.showModal({
    title: "确认接受",
    content: `确定要接受 ${applicant.name} 的申请吗？`,
    success: (res) => {
      if (res.confirm) {
        // 更新申请状态
        // applicant.status = 'accepted';
        acceptApplicant(applicant);

        Taro.showToast({
          title: "已提交",
          icon: "success",
          duration: 2000,
        });

        // 这里可以调用API提交接受申请
        console.log("接受申请：", applicant.id);
      }
    },
  });
};

const acceptApplicant = (applicant) => {
  const type = Taro.getCurrentInstance().router.params.type;
  const urlMaps = {
    0: "/recruitmentDaily/updateSignUp",
    1: "/task/confirmExecution",
    2: "/pages/post/my-publish",
  };

  post(urlMaps[type], {
    id: applicant.id,
    status: 1,
  }).then((res) => {
    console.log("接受申请：", res);
  });
};

/**
 * 拒绝申请
 * @param {Object} applicant - 申请用户信息
 */
const handleReject = (applicant) => {
  if (applicant.status === "accepted" || applicant.status === "rejected") {
    return;
  }

  Taro.showModal({
    title: "确认拒绝",
    content: `确定要拒绝 ${applicant.name} 的申请吗？`,
    success: (res) => {
      if (res.confirm) {
        // 更新申请状态
        applicant.status = "rejected";

        Taro.showToast({
          title: "已提交",
          icon: "success",
          duration: 2000,
        });

        // 这里可以调用API提交拒绝申请
        console.log("拒绝申请：", applicant.id);
      }
    },
  });
};

const checkProces = (applicant) => {
  if (type == 0) {
    Taro.navigateTo({
      url: `/pages-detail/post/recruit/order-acceptance-detail?id=${applicant.id}&type=0`,
    });
  } else {
    Taro.navigateTo({
      url: `/pages/webs/task-details-reward-task-platform?id=${applicant.task_id}&type=1`,
    });
  }
};

/**
 * 跳转到用户详情页
 * @param {Object} applicant - 申请用户信息
 */
function goToUserDetail(applicant) {
  if (!applicant.member_id) return;
  Taro.navigateTo({
    url: `/pages/mine/other?id=${applicant.member_id}`,
  });
}

// 页面加载时获取数据
onMounted(() => {
  //获取路由参数的'id'
  // const courseId = getCurrentInstance();
  // const taskId = courseId.router?.params.taskId || "";

  // if (taskId) {
  //   // 根据任务ID加载对应的申请用户数据
  //   console.log("加载任务ID：", taskId);
  //   // 这里可以调用API获取申请用户列表
  // }

  // getTheDailyClosingInformation(taskId);

  // getSignUpList(taskId);
  getSignUpList(props.tid);

  // 获取任务信息并判断用户角色
  if (props.tid) {
    getTheDailyClosingInformation(props.tid);
  }
});

//const id = Taro.getCurrentInstance().router?.params.id;

//获取该订单信息
const getTheDailyClosingInformation = async (taskId) => {
  const urls = {
    0: "/recruitmentDaily/getById",
    1: "/task/detail",
    2: "/recruitment/getById",
    3: "/check/detail",
  };
  console.log("urls[type]==>", urls[type]);
  const res = await post(urls[type], {
    id: taskId,
  });
  receiveData.value = res.data.columns;

  // 计算薪资：天数 * 日薪 = 总金额
  if(type == 3){
    totalAmount.value = receiveData.value.task_amount;
    return;
  }
  if (receiveData.value && receiveData.value.start_date && receiveData.value.end_date) {
    const days = calculateDays(receiveData.value.start_date, receiveData.value.end_date);
    const dailySalary = Number(receiveData.value.salary || 180); // 日薪，默认180
    const calculatedTotalAmount = days * dailySalary;
    totalAmount.value = calculatedTotalAmount;

    console.log("薪资计算详情:", {
      startDate: receiveData.value.start_date,
      endDate: receiveData.value.end_date,
      days: days,
      dailySalary: dailySalary,
      calculatedTotalAmount: calculatedTotalAmount,
      propsTotalAmount: props.totalAmount,
    });

    // 如果传入的 totalAmount 为0，使用计算值
    if (props.totalAmount === 0) {
      receiveData.value.total_amount = calculatedTotalAmount;
    }
  }
};

//更改状态文本
const change = (status) => {
  switch (status) {
    case 1:
      return "招聘中";
    default:
      return "停止招聘";
  }
};

// 申请用户列表
const getSignUpList = async (id) => {
  const urls = {
    0: "/recruitmentDaily/signUpList",
    1: "/task/signUpList",
    2: "/recruitment/signUpList",
    3: "/check/signUpList",
  };
  const res = await post(urls[type], {
    id: id,
    taskId: id,
  });
  if (res.code == 0) {
    registrationList.value = res.data.map((item) => ({
      ...item.columns,
    }));
    console.log("申请用户列表==>", res.data);
    emit("list", res.data);
  }
};
</script>

<style lang="scss">
// 头像样式优化
.user-avatar {
  border: 2rpx solid #e5e7eb;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

// 确保头像在加载失败时有合适的显示
image {
  background-color: #f3f4f6;
}
.nut-button__wrap{
  white-space: nowrap;
}
</style>
